package etcd

import (
	"stock_app/models"
	"time"

	"github.com/spf13/viper"
	"go.etcd.io/etcd/clientv3"
)

const (
	// 任务保存目录
	JOB_SAVE_DIR = "/cron/jobs/"

	// 任务强杀目录
	JOB_KILLER_DIR = "/cron/killer/"

	// 任务锁目录
	JOB_LOCK_DIR = "/cron/lock/"

	// 服务注册目录
	JOB_WORKER_DIR = "/cron/workers/"

	// 保存任务事件
	JOB_EVENT_SAVE = 1

	// 删除任务事件
	JOB_EVENT_DELETE = 2

	// 强杀任务事件
	JOB_EVENT_KILL = 3
)

var (
	etcdDb *models.EtcdDb
)

// 初始化管理器
func Init() (err error) {
	var (
		config clientv3.Config
		client *clientv3.Client
		kv     clientv3.KV
		lease  clientv3.Lease
	)

	// 初始化配置
	config = clientv3.Config{
		Endpoints:   viper.GetStringSlice("etcd.etcdEndpoints"),                               // 集群地址
		DialTimeout: time.Duration(viper.GetInt64("etcd.etcdDialTimeout")) * time.Millisecond, // 连接超时
	}

	// 建立连接
	if client, err = clientv3.New(config); err != nil {
		return
	}

	// 得到KV和Lease的API子集
	kv = clientv3.NewKV(client)
	lease = clientv3.NewLease(client)

	// 赋值单例
	etcdDb = &models.EtcdDb{
		Client: client,
		Kv:     kv,
		Lease:  lease,
	}
	return
}

func Close() {
	etcdDb.Client.Close()
}
